package ru.gitverse.deenyy.walp.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ru.gitverse.deenyy.walp.model.*;
import ru.gitverse.deenyy.walp.repository.*;

import java.util.List;

@Service
public class CalculationBatchService {
    @Autowired
    private CalculationBatchRepository calculationBatchRepository;

    @Autowired
    private CalculationRequestRepository calculationRequestRepository;

    @Autowired
    private AngleService angleService;

    public CalculationBatch createCalculationBatch(String name, List<AngleRequest> angleRequests) {
        CalculationBatch calculationBatch = new CalculationBatch();
        calculationBatch.setName(name);

        List<CalculationRequest> requests = angleRequests.stream().map(angleRequest -> {
            CalculationRequest request = new CalculationRequest();
            request.setLeftAngleKL(angleRequest.getLeftAngleKL());
            request.setLeftAngleKR(angleRequest.getLeftAngleKR());
            request.setRightAngleKL(angleRequest.getRightAngleKL());
            request.setRightAngleKR(angleRequest.getRightAngleKR());
            request.setCalculationBatch(calculationBatch);
            return request;
        }).toList();

        calculationBatch.setRequests(requests);

        calculationBatchRepository.save(calculationBatch);

        return calculationBatch;
    }

    public CalculationBatch calculateAndSaveGammaForBatch(Long batchId) {
        CalculationBatch calculationBatch = calculationBatchRepository.findById(batchId).orElseThrow(() -> new RuntimeException("Batch not found"));

        List<GammaCalculationResult> results = calculationBatch.getRequests().stream().map(request -> {
            return angleService.calculateAndSaveGamma(request.getLeftAngleKL(), request.getLeftAngleKR(), request.getRightAngleKL(), request.getRightAngleKR());
        }).toList();

        calculationBatch.setResults(results);

        calculationBatchRepository.save(calculationBatch);

        return calculationBatch;
    }
}
